// import {config, errorCode, errorCodeByType, constans} from './config.js'
// import ajax from './api.js'
// import Vue from '@/main'

import axios from 'axios'

import { apis } from './apiConfig'
import axiosConfig from './axiosConfig'

// axios.defaults.headers.post['Content-Type']='application/json;charse=UTF-8'

class Ajax {

	constructor() {}

	// 从配置表中获取参数配置
	getInterface(key) {
		return apis[key];
	}

	// 只需要params， data的简单调用
	getResponse(key, params, data) {
		if(!key) {
			console.error('接口key值不能为空')
			return;
		}
		return this.do(key, {params, data});
	}

	async do(key, usageConfig, expand) {
		let apiInfo = this.getInterface(key) || { url: '' }
		let url = apiInfo.url;
		let config = Object.assign({}, axiosConfig, this.initConfig(apiInfo), usageConfig, this.initConfig({expand}, url));
		let res = await axios(config)
		return res
	}

	// 初始化扩展 -> {headers: 'json'}
	initConfig(config, url) {
		let expand = config.expand;
		if(expand) {
			let keys = Object.keys(expand);
			keys.forEach(key => {
				let handleName = 'set' + key[0].toUpperCase() + key.substring(1)
				this[handleName] && Object.assign(config, this[handleName](expand[key], url));
			});
			delete config.expand
		}
		return config
	}

	// 设置header
	setHeaders(header) {
		header = header.toUpperCase()
		let val = ''
		switch(header) {
			case 'FORM':
				val = 'application/x-www-form-urlencoded; charset=UTF-8'
				break;
			case 'JSON':
				val = 'application/json; charset=UTF-8'
				break;
		}
		return { headers: { 'Content-Type': val , a: 2}}
	}

	// 设置url替换参数
	setUrlReplace(replace, url) {
		for(let field in replace) {
			url = url.indexOf(field) >= 0 ? url.replace(field, replace[field]) : url;
		}
		return { url: url}
	}


	// 设置响应数据
	setResDataFormmat() {

	}

	// 设置请求数据
	setReqDataFormmat() {

	}
}
export default Ajax
